using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



namespace SecretTest.Models
{
    /// <summary>
    /// 加密类
    /// </summary>
    internal class MyEncoder
    {   //public 属性首字母大写
        /// <summary>
        /// 明文
        /// </summary>
        public string Plaintext { get; set; }

        /// <summary>
        /// 密文
        /// </summary>
        public string Cypher { get; set; }

        /// <summary>
        /// 密钥
        /// </summary>
        public string Key { get; set; }

        /// <summary>
        /// 加密动作
        /// </summary>
        public void Encode()
        {
            //将字符串转为字符型数组
            char[] plainAfter = Plaintext.ToCharArray();
            char[] keyAfter = Key.ToCharArray();
            
            //密钥长度
            int length = Key.Length;

            //明文长度
            int length1=Plaintext.Length;

            //创建一个字符型数组装cypher
            char[] cypherAfter = new char[length1];
            
            //开始加密
            for (int i = 0; i < length1; i++)
            {
                //先计算数字,可能会超出26
               int a= (myFunction(plainAfter[i]) + myFunction(keyAfter[i % length]))%26;
                
                //转换为字符
                cypherAfter[i] = Convert.ToChar('a' + a);
                
            }
            //给密文赋值，要new否则会出错！
            Cypher = new string(cypherAfter);

        }

        /// <summary>
        ///从0开始返回指定字符在字母表中的·序号
        /// </summary>
        /// <param name="letter"></param>
        /// <returns></returns>
        private int myFunction(char letter)
        {
            return letter - 'a';
        }
    }

}



